<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Layout Hook Class
 *
 * @package		Application
 * @subpackage	Hooks
 * @category	Layout
 * @author		PC4 Dev Team
 */

class CI_Layout_Hook {
	
	public $base_url;
	var $CI;
	
	/**
	 * Executa as implementa��es de layout.
	 * @return NULL
	 */
	public function init()	{
		
		log_message('debug', "CI_Layout_Hooks Class Initialized");
		
		// Recuperando o objeto do CI, a URL Base e a sa�da da p�gina.
		$CI =& get_instance();
		$this->base_url = str_replace('index.php/', '', $CI->config->item('base_url'));
		$output = $CI->output->get_output();
		
		// Cria o t�tulo da p�gina, meta tags e links para CSS e Javascript
		$title = (isset($CI->layout->title)) ? $CI->layout->title : APPLICATION_TITLE;
		$css = (isset($CI->layout->css)) ? $this->createCSSHTML($CI->layout->css) : '';
		$js = (isset($CI->layout->js)) ? $this->createJSHTML($CI->layout->js) : '';
		$metatag = (isset($CI->layout->metatag)) ? $this->createMetaTagHTML($CI->layout->metatag) : '';
		$dados = (array)$CI->layout->getDados();
		
		 // Verifica se outro layout foi definido, sen�o chama o layout blank.
		if (isset($CI->layout->view) && !preg_match('/(.+).php$/', $CI->layout->view)){
			$CI->layout->view .= '.php';
		}
		else{
			$CI->layout->view = 'blank.php';
		}
		
		// Se o arquivo de layout n�o existir. 
		$layout = LAYOUTPATH . $CI->layout->view;
		if ($CI->layout->view !== 'default.php' && !file_exists(APPPATH . 'views/' . $layout) && !file_exists(BASEPATH . 'libraries/PC4/views/' . $layout)){
			if ($CI->layout->view != '.php') show_error("You have specified a invalid layout: " . $CI->layout->view);
		}
		
		// Se o arquivo layout existir. 
		if (file_exists(APPPATH . 'views/' . $layout) || file_exists(BASEPATH . 'libraries/PC4/views/' . $layout)){
			$layout = $CI->load->view($layout, $dados, true);
			$view = str_replace('{content_for_layout}', $output, $layout);
			$view = str_replace('{title_for_layout}', $title, $view);
			$view = str_replace('{css_for_layout}', $css, $view);
			$view = str_replace('{js_for_layout}', $js, $view);
			$view = str_replace('{metatag_for_layout}', $metatag, $view);
			$view = str_replace('{base_url}', substr($this->base_url, 0, (strlen($this->base_url) - 1)), $view); //NO TRAILING SLASH
		}
		else{
			$view = $output;
		}
		echo $view;
	}
	
	/**
	 * Gera o c�digo HTML das inser��es de CSSs utilizados no layout.
	 * @param array $links Array com CSSs que devem ser inseridos no layout.
	 * @param string $conditional Condi��o para uso de CSSs com Coment�rios Condicionais.
	 * @return string C�digo HTML de inser��o de CSSs.
	 */
	private function createCSSHTML($links){
		$html = "";
		foreach($links as $conditional => $link){
			if($conditional != "normal"){
				$link = array_unique($link);		
				for ($i = 0; $i < count($link); $i++){
					$html .= "\t\t<!--[$conditional]>\n";
					if(stristr($link[$i], "http://") === false){
						$html .= "\t\t<link rel='stylesheet' type='text/css' href='" . $this->base_url . CSSPATH . $this->completaExtensao($link[$i], 'css') . "' media='screen' />\n";
					}
					else{
						$html .= "\t\t<link rel='stylesheet' type='text/css' href='" . $this->completaExtensao($link[$i], 'css') . "' media='screen' />\n";
					}
					$html .= "\t\t<![endif]-->\n";
				}
			}
			else{
				$link = array_unique($link);		
				for ($i = 0; $i < count($link); $i++){
					if(stristr($link[$i], "http://") === false){
						$html .= "\t\t<link rel='stylesheet' type='text/css' href='" . $this->base_url . CSSPATH . $this->completaExtensao($link[$i], 'css') . "' media='screen' />\n";
					}
					else{
						$html .= "\t\t<link rel='stylesheet' type='text/css' href='" . $this->completaExtensao($link[$i], 'css') . "' media='screen' />\n";
					}
				}
			}
		}
		return $html;
	}
	
	/**
	 * Gera o c�digo HTML das inser��es de JavaScripts utilizados no layout.
	 * @param array $links Array com JavaScripts que devem ser inseridos no layout.
	 * @return string C�digo HTML de inser��o de JavaScripts.
	 */
	private function createJSHTML($linksRepetidos){
		$links = array_unique($linksRepetidos);
		$html = "";
		foreach ($links as $link){
			if(stristr($link, "http://") === false){
				$html .= "\t\t<script type='text/javascript' src='" . $this->base_url . JSPATH . $link . "'></script>\n";
			}
			else{
				$html .= "\t\t<script type='text/javascript' src='" . $link . "'></script>\n";
			}
		}
		return $html;
	}
	/**
	 * Gera o c�digo HTML das inser��es de Meta Tags utilizados no layout.
	 * @param array $metas Array com Meta Tags que devem ser inseridos no layout.
	 * @return string C�digo HTMl de inser��es de Meta Tag.
	 */
	private function createMetaTagHTML($metas){
		$html = "";
		foreach($metas as $name => $content){
			$html .= "\t\t<meta name='" . $name . "' content='". $content . "' />\n";
		}
		return $html;
	}
	
	private function completaExtensao($arquivo, $ext) {
		$p = strrpos($arquivo, '.' . $ext);
		if ($p === false || $p != (strlen($arquivo) - strlen('.' . $ext))) {
			return $arquivo . '.' . $ext;
		}
		return $arquivo;
	}
	
}